/**
 * Created by hiibook on 2017/6/15.
 */
var wechatMsgConstruct = require('./wechatMsgConstruct');
var config = require('../config/config');
module.exports = function (req, res, next) {
    console.log('用户注册');
    if (req.wechatMsg.MsgType == "text") {
        switch (true) {
            case /科学上网/.test(req.wechatMsg.Content):
            case /飞机票/.test(req.wechatMsg.Content):
                console.log('接受命令');
                Registered(req, res, next);
                break;
            default:
                next();
                break;
        }
    } else {
        next()
    }

    function Registered(req, res, next) {
        if(req.wechatUserStatus){
            var chat = {
                Type: "text",
                Content: "您已经是我们的会员，发送帮助查看使用说明"
            };
            // 最后一步需要信息,并关闭数据库连接
            req.mysqlConnection.end();
            res.send(wechatMsgConstruct(req.wechatMsg, chat));
        }else{
            var registeredStatus = null;
            var query = req.mysqlConnection.query("insert into ss_user (available,account_type,open_id,pass,transfer_enable,protocol,obfs,switch,enable,method) values (1,'default','" + req.wechatMsg.FromUserName + "','123456',"+config.defaultTraffic*1024576+",'origin','plain',1,1,'"+config.defaultMethod+"')");//炒作数据库
            query
                .on('error', function (err) {
                    console.log('数据库连接失败', err)
                })
                .on('result', function (row) {
                    registeredStatus = row;
                })
                .on('end', function () {
                    if (registeredStatus == null){

                        var chat = {
                            Type: "text",
                            Content: "与你对口令的人出了毛病，您可以稍后再试"
                        };
                        // 最后一步需要信息,并关闭数据库连接
                        req.mysqlConnection.end();
                        res.send(wechatMsgConstruct(req.wechatMsg, chat));
                    }else {
                        var chat = {
                            Type: "text",
                            Content: "可以，你是我们自己人了！您可以发送帮助或说明等来查看使用方法"
                        };
                        // 最后一步需要信息,并关闭数据库连接
                        req.mysqlConnection.end();
                        res.send(wechatMsgConstruct(req.wechatMsg, chat));
                    }

                });
        }

    }

};